<!--
 * @Author       : wfl
 * @LastEditors: ww
 * @description  :
 * @updateInfo   :
 * @Date         : 2023-05-10 10:39:08
 * @LastEditTime: 2023-06-30 11:00:28
-->
<script setup lang="ts" name="ApprovalTable">
import { ikStore } from 'iking-utils'
import { useFields } from './fields'
import { approvalApi } from '@/MainApp/apis/approval'

const props = defineProps({
  noTitle: {
    type: Boolean,
    default: false
  },
  tab: {
    type: String || Number,
    default: ''
  }
})

const activeName: any = inject('activeName')
const activeTab: any = inject('activeTab')
const userInfo = ikStore.local.getItem('user_info')
const formDefault: object = {
  name: '',
  createUser: ''
}
const handoverData = ref<any>([])
const tableFieldList = ref<any>([])
const { fieldList, flowFieldList, ISubmitFieldList, CopyForMeFieldList }
  = useFields()
const tadaTotal = ref(0)
// 组件返回的查询参数，包含分页和查询字段
const pageData = ref()
const approveFlowStore = useApproveFlowStore()
const { loading } = usePages(() => {
  queryData()
})
const queryData = async () => {
  loading.value = true
  const param: any = {
    ...formDefault,
    ...pageData.value
  }

  switch (activeName.value) {
    case EApproveListTab.我审批的:
      param.executorUserId = userInfo?.id
      if (activeTab.value === EApprovedType.待审列表) {
        tableFieldList.value = fieldList.value
        param.approvedByExecutorUser = false
      }
      if (activeTab.value === EApprovedType.已审列表) {
        tableFieldList.value = flowFieldList.value
        param.approvedByExecutorUser = true
      }
      break
    case EApproveListTab.抄送我的:
      param.carbonCopyUserId = userInfo?.id
      tableFieldList.value = CopyForMeFieldList.value
      break
    case EApproveListTab.我提交的:
      param.initiatorIds = [userInfo?.id]
      tableFieldList.value = ISubmitFieldList.value
      break
    case EApproveListTab.分享给我:
      tableFieldList.value = fieldList.value
      param.initiatorIds = userInfo?.id
      break
    default:
      break
  }

  const { success, data, total } = await approvalApi.getListData(param)
  if (success) {
    handoverData.value = success ? data : []
    handoverData.value
      = handoverData.value?.map?.((item: any) => {
        return {
          ...item,
          formDataSummary: JSON.parse(item?.formDataSummary || '{}')
        }
      }) || []
    tadaTotal.value = total
    loading.value = false
  }
}

const viewDetails = (row: any) => {
  approveFlowStore.setShowDetail(true)
  approveFlowStore.setRowData(row)
  // 抄送且未读状态时，调用已读接口
  if (activeName.value === EApproveListTab.抄送我的)
    approvalApi.handReaded({ formInstanceId: row.id })
}

const autoShowDetail = () => {
  const route = useRoute()
  const { id } = route.query as any
  if (id)
    viewDetails({ id })
}
autoShowDetail()

watch(
  () => approveFlowStore.showDetail,
  (v: any) => {
    !v && queryData()
  }
)

watch(
  () => activeTab?.value,
  () => {
    queryData()
  }
)

const getType = (data: any) => {
  let type = 'info'
  switch (data.row.processStatus) {
    case 'APPROVING':
      type = 'warning'
      break
    case 'PASS':
      type = 'success'
      break
    case 'REJECT':
      type = 'error'
      break
    case 'REVOKE':
      type = 'default'
      break
  }
  return type
}
const { user } = useConfig()
const getProcessStatusName = (data: any) => {
  const { processStatusName, currentInstanceUsers } = data.row
  let name = processStatusName
  if (!currentInstanceUsers?.length)
    return name
  try {
    const isSelf = currentInstanceUsers?.findIndex((cur: any) => {
      return cur.userId === user?.id
    })
    let names = ''
    let withMe = ''
    currentInstanceUsers?.forEach((cur: any) => {
      if (cur.userId !== user?.id)
        names += `${cur.userName}/`
    })
    withMe = `我${
      names.length > 0 ? `/${names.substring(0, names.length - 1)}` : ''
    }`

    const baseName = `待${isSelf >= 0 ? withMe : (names.substring(0, names.length - 1) || name)
    }`
    switch (data.row.processStatus) {
      case 'APPROVING':
        name = `${baseName}审批`
        break
      case 'WAIT_FOR_INITIATE':
        name = `${baseName}发起`
        break
    }
    return name
  }
  catch (error) {
    return name
  }
}

onMounted(() => {
  const id = approveFlowStore?.socketInfo?.id
  if (id) {
    nextTick(() => {
      viewDetails({ id })
    })
  }
})

defineExpose({
  queryData,
  viewDetails
})
</script>

<template>
  <IkPageFull
    v-model="pageData"
    :header-title="noTitle ? '' : '审批列表'"
    :fields="tableFieldList"
    :table-data="handoverData"
    :total="tadaTotal"
    :loading="loading"
    :search="queryData"
    :tab-id="tab"
  >
    <template #formDataSummary="{ data: { row } }">
      <div
        v-for="(item, index) in row.formDataSummary"
        :key="index"
        class="summary-cen"
      >
        <div class="summary-left">{{ item?.label }}:</div>
        <div class="summary-right">{{ item?.value }}</div>
      </div>
    </template>
    <template #processStatusName="{ data }">
      <IkColorText :type="getType(data)">
        {{ getProcessStatusName(data) }}
      </IkColorText>
    </template>
    <template #carbonCopyReadStatusName="{ data }">
      <IkColorText
        :type="data.row.carbonCopyReadStatus === 'READ' ? 'success' : 'warning'"
      >
        {{ data.row.carbonCopyReadStatusName }}
      </IkColorText>
    </template>
    <template #operate="{ data }">
      <IkSvgIcon
        name="iksvg_liebiao"
        show-bg
        :start-margin="false"
        title="详情"
        pop
        in-table
        @click="viewDetails(data.row)"
      />
    </template>
  </IkPageFull>
</template>

<style lang="scss" scoped>
.summary-cen {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  flex: 5;
  // font-weight: 400;
  // font-style: normal;
  // color: #999999;
  .summary-left {
    // display: flex;
    // justify-content: flex-end !important;
    // flex: 2;
    margin-right: 8px;
  }

  .summary-right {
    flex: 3;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
</style>
